import { AI_CONFIG } from '../config/aiConfig';
import { AGENT_CONFIGS, AgentConfig, getAgentConfig } from '../config/agentConfig';
import OpenAI from 'openai';

// 多Agent协作接口
interface AgentCollaborationChain {
  primaryAgent: string;
  supportingAgents: string[];
  collaborationPattern: string;
  dataExchangePoints: string[];
}

const thinkingEndStatement = "\n\n思考已完成，正在总结和生成最终结果中，请稍候...";
export class ThinkingProcessService {
  private static instance: ThinkingProcessService;
  private client: OpenAI;
  
  // 添加debug开关
  private debugMode: boolean = process.env.NODE_ENV === 'development';

  private constructor() {
    this.client = new OpenAI({
      apiKey: AI_CONFIG.QWEN_OMNI.API_KEY,
      baseURL: AI_CONFIG.QWEN_OMNI.BASE_URL,
      dangerouslyAllowBrowser: true
    });
    
    // Debug信息
    if (this.debugMode) {
      console.log('🤖 [ThinkingProcessService] 初始化完成');
      console.log('🔧 [Debug] 可用Agent配置:', Object.keys(AGENT_CONFIGS));
    }
  }

  public static getInstance(): ThinkingProcessService {
    if (!ThinkingProcessService.instance) {
      ThinkingProcessService.instance = new ThinkingProcessService();
    }
    return ThinkingProcessService.instance;
  }

  /**
   * 流式输出：生成Agent思考过程
   */
  public async getThinkingStepsStream(
    query: string, 
    onContentUpdate: (content: string) => void
  ): Promise<void> {
    
    await new Promise(resolve => setTimeout(resolve, 1500));
    const collaborationChain = await this.detectMultiAgentCollaboration(query);
    
    if (collaborationChain.supportingAgents.length > 0) {
      // 生成多Agent协作思考过程（流式）
      await this.generateMultiAgentThinkingStepsStream(
        collaborationChain, 
        query, 
        onContentUpdate,
      );
    } else {
      const agentConfig = getAgentConfig(collaborationChain.primaryAgent);
      if (!agentConfig) {
        throw new Error('Agent configuration not found');
      }
      let result = await this.generateSingleAgentThinkingStream(
        agentConfig,
        query,
        onContentUpdate,
      );
      onContentUpdate(result + thinkingEndStatement);
    }
    
  }

  /**
   * 多Agent协作检测
   */
  private async detectMultiAgentCollaboration(
    query: string, 
  ): Promise<AgentCollaborationChain> {
    
    // 第一步：路由到主Agent
    const primaryAgent = await this.routeToAgent(query);
    const primaryConfig = getAgentConfig(primaryAgent);
    
    if (!primaryConfig) {
      if (this.debugMode) {
        console.log('⚠️ [Debug] 未找到主Agent配置，使用默认Agent');
      }
      return {
        primaryAgent: 'FinancialDefaultAgent',
        supportingAgents: [],
        collaborationPattern: 'single',
        dataExchangePoints: []
      };
    }
    
    
    let supportingAgents: string[] = [];
    let collaborationPattern = 'single';
    let dataExchangePoints: string[] = [];
    
    // 确定需要协作的Agent
    supportingAgents = primaryConfig.collaboration.supportingAgents;
    collaborationPattern = supportingAgents.length > 1 ? 'multi-stage' : 'dual-agent';
    dataExchangePoints = primaryConfig.collaboration.dataExchangePoints;
        
    if (this.debugMode) {
      console.log('🤝 [Debug] 需要协作，支持Agent:', supportingAgents);
    }
    
    const result: AgentCollaborationChain = {
      primaryAgent,
      supportingAgents,
      collaborationPattern,
      dataExchangePoints
    };
    
    return result;
  }

  /**
   * 生成单Agent思考内容（流式版本）
   */
  private async generateSingleAgentThinkingStream(
    agentConfig: AgentConfig,
    query: string,
    onChunkUpdate: (chunk: string) => void
  ): Promise<string> {
    
    const prompt = this.buildEnhancedAgentPrompt(agentConfig, query);
    const systemContent = `你是一个名叫${agentConfig.name}的AI智能体，你的角色是${agentConfig.promptTemplate.systemRole}`;
    
    let result = '';
    
    await this.callOpenAIStream(
      systemContent,
      prompt,
      (chunk) => {
        result = chunk;
          onChunkUpdate(chunk);
      },
      700
    );
    
    return result || '正在分析问题和需求...';
  }

  /**
   * 流式输出：生成多Agent协作思考过程
   */
  private async generateMultiAgentThinkingStepsStream(
    collaborationChain: AgentCollaborationChain,
    query: string,
    onContentUpdate: (content: string) => void,
  ): Promise<void> {
    
    console.log('🤝 [Debug] generateMultiAgentThinkingStepsStream 开始');
    
    const primaryConfig = getAgentConfig(collaborationChain.primaryAgent);
    
    if (!primaryConfig) {
      console.log('❌ [Debug] 未找到主Agent配置');
      onContentUpdate('未找到主Agent配置，使用默认思考过程...');
      return;
    }
    
    console.log(`✅ [Debug] 主Agent: ${primaryConfig.name}`);
    console.log(`🔗 [Debug] 协作Agents: ${collaborationChain.supportingAgents.length}个`);
    
    let primaryContent = '';
    let collaborationContent = '';
    
    // 主Agent思考过程
    onContentUpdate(`【${primaryConfig.name} 主分析】\n正在分析问题...`);
    
    try {
      await this.generateSingleAgentThinkingStream(
        primaryConfig, 
        query,
        (chunk) => {
          primaryContent = `【${primaryConfig.name}】\n${chunk}`;
          const fullContent = collaborationContent ? 
            `${primaryContent}\n\n${collaborationContent}` : 
            primaryContent;
          onContentUpdate(fullContent);
        }
      );
    } catch (error) {
      console.error('主Agent思考生成失败:', error);
      primaryContent = `【${primaryConfig.name} 主分析】\n分析问题和需求...`;
      onContentUpdate(primaryContent);
    }
    
    // 协作Agent思考过程
    if (collaborationChain.supportingAgents.length > 0) {
      const supportingNames = collaborationChain.supportingAgents
        .map(id => getAgentConfig(id)?.name)
        .filter(name => name)
        .join('、');
      
      console.log(`🔗 [Debug] 开始协作Agent分析: ${supportingNames}`);
      
      const supportingThoughts: string[] = [];
      
      for (let i = 0; i < collaborationChain.supportingAgents.length; i++) {
        const agentId = collaborationChain.supportingAgents[i];
        const agentConfig = getAgentConfig(agentId);
        if (agentConfig) {
          console.log(`🔗 [Debug] 处理协作Agent: ${agentConfig.name}`);
          
          // 初始化协作Agent的思考内容
          supportingThoughts.push(`【${agentConfig.name}】\n正在分析...`);
          
          // 更新协作内容
          collaborationContent = supportingThoughts.join('\n\n');
          const fullContent = `${primaryContent}\n\n${collaborationContent}`;
          onContentUpdate(fullContent);
          
          try {
            await this.generateSingleAgentThinkingStream(
              agentConfig, 
              query,
              (chunk) => {
                // 更新当前Agent的思考内容
                supportingThoughts[i] = `【${agentConfig.name} 协作分析】\n${chunk}`;
                
                // 重新构建协作内容
                collaborationContent = supportingThoughts.join('\n\n');
                const fullContent = `${primaryContent}\n\n${collaborationContent}`;
                onContentUpdate(fullContent);
              }
            );
            await new Promise(resolve => setTimeout(resolve, 1000));
          } catch (error) {
            console.error(`协作Agent ${agentConfig.name} 思考生成失败:`, error);
            supportingThoughts[i] = `【${agentConfig.name} 协作分析】\n补充分析中...`;
            collaborationContent = supportingThoughts.join('\n\n');
            const fullContent = `${primaryContent}\n\n${collaborationContent}`;
            onContentUpdate(fullContent);
          }
        }
      }
    }
    
    // 添加思考完成提示
    const fullContent = `${primaryContent}\n\n${collaborationContent}\n\n${thinkingEndStatement}`;
    onContentUpdate(fullContent);
    console.log('🏁 [Debug] generateMultiAgentThinkingStepsStream 完成');
  }

  private buildEnhancedAgentPrompt(
    agentConfig: AgentConfig,
    query: string,
  ): string {
    const thinkingChain = agentConfig.promptTemplate.thinkingChain.map((step, index) => `${index + 1}. ${step}`).join('\n');
    return `用户问题："${query}"，
    你的核心思考流程：${thinkingChain}，
    你可以调用的工具的名字和描述：${agentConfig.tools.map(tool => tool.name + '：' + tool.description).join(', ')}，
    请展示你的思考过程，分析方向和计划调用的工具，逐步分析问题，生成4段内容，每一段内容不超过300字，以换行符分割，不要使用markdown`;
  }

  /**
   * 通用的流式OpenAI API调用方法
   */
  private async callOpenAIStream(
    systemContent: string,
    userContent: string,
    onChunk: (chunk: string) => void,
    maxTokens: number = 700
  ): Promise<void> {
    try {
      const completion = await this.client.chat.completions.create({
        model: AI_CONFIG.QWEN_OMNI.MODEL,
        messages: [
          { role: "system", content: systemContent },
          { role: "user", content: userContent }
        ],
        temperature: 0.1,
        max_tokens: maxTokens,
        stream: true
      });
      
      let fullResponse = '';
      
      for await (const chunk of completion) {
        const delta = chunk.choices[0]?.delta?.content || '';
        if (delta) {
          fullResponse += delta;
          onChunk(fullResponse);
          await new Promise(resolve => setTimeout(resolve, 150)); 
        }
      }
    } catch (error) {
      console.error('OpenAI API调用失败:', error);
      onChunk('思考过程生成失败，请重试...');
    }
  }

  /**
   * 核心功能：Agent路由逻辑（升级版 - 使用大语言模型路由）
   */
  private async routeToAgent(query: string): Promise<string> {
    const routingStartTime = Date.now();
    
    if (this.debugMode) {
      console.log('🔄 [Debug] 开始LLM Agent路由分析');
      console.log('📝 [Debug] 路由查询:', query);
    }
    
    // 第一步：文档分析优先级最高（快速规则）
    if (this.containsDocumentIndicators(query)) {
      if (this.debugMode) {
        console.log('📄 [Debug] 检测到文档分析需求 → FinancialAnalyzeReportsAgent');
      }
      return 'FinancialAnalyzeReportsAgent';
    }
    
    // 第二步：明确的产品代码分析（快速规则）
    if (this.hasProductCode(query)) {
      if (this.debugMode) {
        console.log('🔍 [Debug] 检测到产品代码 → FinancialProductAnalysisAgent');
      }
      return 'FinancialProductAnalysisAgent';
    }
    
    // 第三步：使用LLM进行智能路由
    const routingResult = await this.performLLMRouting(query);
    
    if (this.debugMode) {
      const routingDuration = Date.now() - routingStartTime;
      console.log(`🎯 [Debug] 路由到Agent: ${routingResult} (耗时: ${routingDuration}ms)`);
    }
    
    return routingResult;
  }

  /**
   * 基于大语言模型的智能路由
   */
  private async performLLMRouting(query: string): Promise<string> {
    try {
      const prompt = this.buildRoutingPrompt(query);
      
      if (this.debugMode) {
        console.log('🤖 [Debug] 发送LLM路由请求');
      }
      
      const completion = await this.client.chat.completions.create({
        model: AI_CONFIG.QWEN_OMNI.MODEL,
        messages: [
          {
            role: "system",
            content: "你是一个专业的Agent路由系统，需要根据用户查询选择最合适的Agent。"
          },
          {
            role: "user",
            content: prompt
          }
        ],
        temperature: 0.1, // 使用低温度确保稳定性
        max_tokens: 50   // 只需要返回Agent ID
      }, {
        timeout: 5000     
      });
      
      const selectedAgent = completion.choices[0]?.message?.content?.trim() || '';
      
      if (this.debugMode) {
        console.log('🎯 [Debug] LLM路由结果:', selectedAgent);
      }
      
      // 验证Agent ID是否有效
      const validAgent = this.validateAgentId(selectedAgent);
      
      return validAgent;
      
    } catch (error) {
      console.error('🚨 [Error] LLM路由失败，使用回退策略:', error);
      
      // 回退到关键词匹配
      return this.performKeywordRouting(query);
    }
  }

  /**
   * 构建路由提示词
   */
  private buildRoutingPrompt(query: string): string {
    // 构建Agent描述
    const agentDescriptions = Object.values(AGENT_CONFIGS).map(agent => 
      `${agent.id}: ${agent.name} - ${agent.description}\n关键领域: ${agent.routingKeywords.join(', ')}`
    ).join('\n\n');

    return `你是一个专业的Agent路由系统，你拥有丰富的金融知识，知道一个金融问题需要哪些agent去处理，需要根据用户查询选择最合适的Agent。

可用Agent列表：
${agentDescriptions}

用户查询："${query}"

路由规则：
1. 分析用户的核心需求和意图
2. 匹配最专业的金融Agent处理该问题
3. 如果涉及文档/财报分析，选择FinancialAnalyzeReportsAgent
4. 如果包含具体基金代码或者询问股票/债券/基金等金融产品的信息，选择FinancialProductAnalysisAgent
5. 如果是推荐/选择请求，选择FinancialProductSelectionAgent
6. 如果是询问能不能买/卖，持仓调整配置/组合相关，选择FinancialInvestFolioToolAgent
7. 如果是市场/行情分析，选择FinancialAnalyzeMarketAgent
8. 如果是营销/话术相关，选择MarketingAgent
9. 其他一般问题选择FinancialDefaultAgent

请只返回最合适的Agent ID，不要其他内容。`;
  }

  /**
   * 验证Agent ID
   */
  private validateAgentId(agentId: string): string {
    // 检查是否为有效的Agent ID
    if (AGENT_CONFIGS[agentId]) {
      return agentId;
    }
    
    // 如果不是有效ID，尝试模糊匹配
    const possibleMatches = Object.keys(AGENT_CONFIGS).filter(id => 
      id.toLowerCase().includes(agentId.toLowerCase()) || 
      agentId.toLowerCase().includes(id.toLowerCase())
    );
    
    if (possibleMatches.length > 0) {
      if (this.debugMode) {
        console.log('🔧 [Debug] 模糊匹配到Agent:', possibleMatches[0]);
      }
      return possibleMatches[0];
    }
    
    // 默认返回通用Agent
    console.warn('⚠️ [Warning] 无效的Agent ID，使用默认Agent:', agentId);
    return 'FinancialDefaultAgent';
  }

  /**
   * 关键词路由回退方案
   */
  private performKeywordRouting(query: string): string {
    const queryLower = query.toLowerCase();
    
    // 简化的关键词匹配逻辑
    const keywordMap = {
      'FinancialAnalyzeMarketAgent': ['市场', '行情', '大盘', '指数', '宏观'],
      'FinancialProductAnalysisAgent': ['基金', '产品', '分析', '代码'],
      'FinancialProductSelectionAgent': ['推荐', '选择', '什么', '哪个'],
      'FinancialInvestFolioToolAgent': ['配置', '组合', '资产', '分配'],
      'FinancialAnalyzeReportsAgent': ['财报', '研报', '报告', '文档'],
      'MarketingAgent': ['营销', '话术', '策略', '沟通']
    };
    
    for (const [agentId, keywords] of Object.entries(keywordMap)) {
      if (keywords.some(keyword => queryLower.includes(keyword))) {
        if (this.debugMode) {
          console.log('🔄 [Debug] 关键词匹配到Agent:', agentId);
        }
        return agentId;
      }
    }
    
    return 'FinancialDefaultAgent';
  }

  /**
   * 检测文档相关指标
   */
  private containsDocumentIndicators(query: string): boolean {
    const documentKeywords = [
      '财报', '研报', '报告', '文档', '分析报告', '年报', '季报', '半年报',
      '财务报表', '企业分析', '上传', '文件', '解读', 'pdf', '附件'
    ];
    
    const queryLower = query.toLowerCase();
    return documentKeywords.some(keyword => queryLower.includes(keyword));
  }

  /**
   * 检查是否包含产品代码（增强版）
   */
  private hasProductCode(query: string): boolean {
    // 基金代码模式匹配
    const patterns = [
      /\b\d{6}\b/,           // 6位数字基金代码
      /\b[A-Z]{2}\d{4}\b/,   // 2字母+4数字
      /\b\d{3}\d{3}\b/,      // 分段的6位数字
    ];
    
    return patterns.some(pattern => pattern.test(query));
  }
} 